/**
 * 
 */
package com.conn.service.socket.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import com.conn.service.socket.req.ClientRequest;
import com.conn.service.socket.req.RequestFactory;

/**
 * @author lushouzhi
 * 
 */
public class RequestDecoder extends CumulativeProtocolDecoder {

	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		// remember the start position
		int start = in.position();
		if (in.remaining() > 4) {
			int length = in.getInt();
			// System.out.println(length);
			if (length < 0) {
				in.position(start);
				return false;
			} else if (in.remaining() < length - 4) {
				in.position(start);
				return false;
			}
			short cmd = in.getShort();
			int reLen=length-6;
			byte []body=new byte[reLen];
			in.get(body, 0, reLen);
			ClientRequest request=RequestFactory.create(cmd);
			request.setBody(body);
			request.parseBody();
			out.write(request);
			return true;
		} else {
			return false;
		}
	}
}
